from rest_framework import serializers

from apps.goods.models import SKU, GoodsCategory, SPU, SKUSpecification


class SKUSpecificationSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKUSpecification
        fields = ['spec_id', 'option_id']


class SKUSerializer(serializers.ModelSerializer):

    spu = serializers.StringRelatedField(read_only=True)
    category = serializers.StringRelatedField(read_only=True)

    spu_id = serializers.IntegerField()
    category_id = serializers.IntegerField()

    specs = SKUSpecificationSerializer(many=True)


    class Meta:
        model = SKU
        fields = '__all__'

    def create(self, validated_data):
        del validated_data['specs']
        data = self.context['request'].data
        specs = data.get('specs')
        object = SKU.objects.create(**validated_data)
        for item in specs:
            SKUSpecification.objects.create(
                sku=object,
                spec_id=item.get('spec_id'),
                option_id=item.get('option_id')
            )
        return object

    def update(self, instance, validated_data):

        del validated_data['specs']
        specs = self.context['request'].data.get('specs')

        pk = self.context['view'].kwargs.get('pk')

        SKU.objects.filter(id=pk).update(**validated_data)

        for item in specs:
            SKUSpecification.objects.filter(
                sku_id=pk,
                spec_id=item.get('spec_id')
            ).update(option_id=item.get('option_id'))
        return instance


class SKUSimpleCategorySerializer(serializers.ModelSerializer):

    class Meta:
        model = GoodsCategory
        fields = ['id', 'name']


class SPUSimpleListSerializer(serializers.ModelSerializer):

    class Meta:
        model = SPU
        fields = ['id', 'name']


class SKUSimpleListSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ['id', 'name']